//
//  ConsulationV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/9/27.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "ConsulationV2ViewController.h"

#import "ConsulationV2AskViewController.h"
#import "ExpertListV2ViewController.h"
#import "ConsulationV2AnswerInfoViewController.h"
#import "ConsulationSearchV2ViewController.h"

#import "ConsulationFunc1Cell.h"
#import "ConsulationNewReplyCell.h"

@interface ConsulationV2ViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) ConsulationV2ViewModel* viewModel;

// UI

//IBOutlet// UI
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;

@end

@implementation ConsulationV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    /// tableView auto rowHeight
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100.0f;
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[ConsulationFunc1Cell class]];
    [self.tableView mh_registerNibCell:[ConsulationNewReplyCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
    self.tabBarItem.title = @"环保咨询";
    self.tabBarItem.image = [[UIImage imageNamed:@"tabbar_consult"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tabbar_consult_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    [[self.viewModel.consulationFunc1CM.askCmd.executionSignals switchToLatest] subscribeNext:^(id x) {
       @strongify(self);
        
        [self _push2AskVC];
    }];
    [[self.viewModel.consulationFunc1CM.askCmd.errors deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
         
        NSError* error = x;
         
        if ([error.domain isEqualToString:SUCommandErrorDomain])
        {
            [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
            return;
        }
        [MBProgressHUD mh_showErrorTips:error];
    }];
    
    [[self.viewModel.consulationFunc1CM.expertCmd.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        
        [self _push2ExpertVC];
    }];
    
    self.viewModel.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath) {
        @strongify(self);
        
        if (indexPath.section == 1)
        {
            [self _push2AnswerInfoVC:indexPath.row];
        }
        
        return [RACSignal empty];
    }];
    
    [self.viewModel.consulationFunc1CM.searchCmd.executionSignals.switchToLatest subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2SearchVC];
    }];
}

#pragma mark - 更新初始化 操作
- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellIdentifier = identifier;
    
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            cellIdentifier = NSStringFromClass([ConsulationFunc1Cell class]);
        }
    }
    else
    {
        cellIdentifier = NSStringFromClass([ConsulationNewReplyCell class]);
    }
    
    return [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}

/// config  data
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(NSObject *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    
    if ([cell isKindOfClass:[ConsulationFunc1Cell class]])
    {
        ConsulationFunc1CellModel* curObj = (ConsulationFunc1CellModel*)object;
        ConsulationFunc1Cell* curCell = (ConsulationFunc1Cell*)cell;
        [curCell bindViewModel:curObj];
    }
    else if ([cell isKindOfClass:[ConsulationNewReplyCell class]])
    {
        ConsulationNewReplyCellModel* curObj = (ConsulationNewReplyCellModel*)object;
        ConsulationNewReplyCell* curCell = (ConsulationNewReplyCell*)cell;
        [curCell bindViewModel:curObj];
    }
}

/// 文本内容区域
- (UIEdgeInsets)contentInset
{
    return UIEdgeInsetsZero;
}

#pragma mark - UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
//    /// 所以笔者采用实现计算好的cell的高度
//
//    return [self.viewModel.dataSource[indexPath.row] cellHeight];
//}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    
    if (indexPath.section == 0)
    {
        object = self.viewModel.consulationFunc1CM;
    }
    else
    {
        object = self.viewModel.dataSource[indexPath.section][indexPath.row];
    }
    
    // bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    
    return cell;
}

#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - Listener
- (void)_btnListener_share
{
    NSLog(@"Stwx Detail Share Btn Click!");
}

- (void)_btnListener_zan
{
    NSLog(@"Stwx Detail Zan Btn Click!");
}

- (void)_btnListener_comment
{
    NSLog(@"Stwx Detail Comment Btn Click!");
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_push2AskVC
{
    ConsulationV2AskViewModel* vm = [[ConsulationV2AskViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"我要咨询"}];
    ConsulationV2AskViewController* vc = [[ConsulationV2AskViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2ExpertVC
{
    ExpertListV2ViewModel* vm = [[ExpertListV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"环保专家列表"}];
    ExpertListV2ViewController* vc = [[ExpertListV2ViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2AnswerInfoVC:(NSInteger)index
{
    ConsulationV2AnswerInfoViewModel* vm = [[ConsulationV2AnswerInfoViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"新回复内容"}];
    vm.consultListData = self.viewModel.dataSource[1][index];
    ConsulationV2AnswerInfoViewController* vc = [[ConsulationV2AnswerInfoViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2SearchVC
{
    ConsulationSearchV2ViewModel* vm = [[ConsulationSearchV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"查询问题库"}];
    ConsulationSearchV2ViewController* vc = [[ConsulationSearchV2ViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

@end



